package org.gd.spring.hibernate;

import org.gd.spring.hibernate.entity.*;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class App1 {

    public static void main( String[] args ) {
        Session session = null;
        try {
            ApplicationContext ac = new ClassPathXmlApplicationContext("hibernate/hibernate.context.xml");
            HibernateUtil hibernateUtil = ac.getBean("hibernateUtil", HibernateUtil.class);
            session = hibernateUtil.openSession();

            session.beginTransaction();

            User user = new User();
            user.setName("user1");
            user.setAddress(new Address("city1", "street1", 10));
            user.setState(State.SUCCESS);
            session.save(user);

            Stock stock = new Stock();
            stock.setStockCode("47151211");
            stock.setStockName("GENM1211");
            stock.setUser(user);
            stock.setEmb(new Emb(true));
            session.save(stock);

            stock = new Stock();
            stock.setStockCode("2342424");
            stock.setStockName("GENM2342421211");
//            stock.setUser(user);
            session.save(stock);

//            User user = (User) session.get(User.class, 10);
//            Stock stock = (Stock) session.get(Stock.class, 20);
//            System.out.println(stock);
//            stock.setUser(user);
//            session.merge(stock);


            session.getTransaction().commit();

            session.beginTransaction();
            //System.out.println(session.get(User.class, 1));

            Query query = session
                    .createQuery("select b from Stock b");
            List list = query.list();
            System.out.println("=================================");
            for(Object o: list) {
                System.out.println(o);
            }
            session.getTransaction().commit();

        } catch (Throwable e) {
            e.printStackTrace(System.err);
        } finally {
            if(session != null) {
                session.close();
            }
        }
    }
}
